package com.wrs.examsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wrs.examsystem.entity.Result.R;
import com.wrs.examsystem.entity.Teacher;
import com.wrs.examsystem.entity.bean.TeacherBean;
import com.wrs.examsystem.mapper.TeacherMapper;
import com.wrs.examsystem.mapper.UserMapper;
import com.wrs.examsystem.service.TeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wrs.examsystem.util.wheel.TeacherUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 王荣升
 * @since 2024-05-15
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    @Resource
    private TeacherMapper teacherMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public R findTeachers() {
        List<Teacher> teachers = teacherMapper.selectList(null);
        List<TeacherBean> teacherBeans = new ArrayList<>();
        for (int i = 0; i < teachers.size(); i++) {
            teacherBeans.add(TeacherUtil.teacherInvertTeacherBean(teachers.get(i)));
        }
        return R.ok().data(teacherBeans);
    }

    @Override
    public R findByTeacherNumber(String teacherNumber) {
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        teacherQueryWrapper.eq("teacher_number",teacherNumber);
        Teacher teacher = teacherMapper.selectOne(teacherQueryWrapper);
        if (teacher == null){
            return R.error().message("不存在该教师或已经被删除");
        }
        return R.ok().data(TeacherUtil.teacherInvertTeacherBean(teacher));
    }

    @Override
    public R deleteByTeacherNumber(String teacherNumber) {
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        teacherQueryWrapper.eq("teacher_number",teacherNumber);
        Teacher teacher = teacherMapper.selectOne(teacherQueryWrapper);
        if (teacher == null){
            return R.error().message("不存在该教师或已经被删除");
        }
        userMapper.deleteById(teacher.getUserId());
        teacherMapper.delete(teacherQueryWrapper);
        return R.ok();
    }

    @Override
    public R checkUser(Teacher checkTeacher) {
        Teacher teacher = teacherMapper.selectById(checkTeacher.getTeacherId());
        if (teacher == null){
            return R.error().message("不存在该教师或已经被删除");
        }
        if (teacher.getTeacherName().equals(checkTeacher.getTeacherName())
                && teacher.getTeacherNumber().equals(checkTeacher.getTeacherNumber())
                && teacher.getTeacherSex().equals(checkTeacher.getTeacherSex())){
            return R.ok();
        }
        return R.error().message("信息不匹配");
    }
}
